<?php


namespace app\data\model;


use think\admin\Model;

class DataDevice extends Model
{
    public function toilet()
    {
        return $this->hasMany(DataCatLog::class,'iot_id','iotId');
    }
    //我的设备
    function my($uid){
       return  $this->where(['member_id'=>$uid])->where(['is_deleted'=>0])
           ->with(['toilet'=> function ($query) {
               //计算当日0点如厕结束时间差 (单位分钟) 前端展示位置数据
               $today = "DATE_FORMAT(NOW(),'%Y-%m-%d 00:00:00')";
               $in_time = "in_time";
               $str = "TIMESTAMPDIFF(MINUTE,{$today},{$in_time})";
               $query->field('*,'.$str.' AS position, date_format(in_time,"%H:%i") as time')
                   ->whereDay('in_time');
           }])
           ->filter(function($item) {
               $item['checked'] = false;
               return $item;
           })
           ->order('create_at desc')->select();
    }
    //添加设备
    function add($data){
        return  $this->insert($data);
    }
    //删除设备
    function del($iotId){
       return  $this->where(['iotId'=>$iotId])->update(['is_deleted'=>1]);
    }
    //开启停用设备
    function setStatus($iotId,$status){
        return  $this->where(['iotId'=>$iotId])->update(['status'=>$status]);
    }
    //上下线
    function setOnline($iotId,$clientIp,$status,$time){
        $data = [
            'status'=>$status,
            'status_update_time'=>$time,
        ];
        if($clientIp!=''){
            $data['client_ip'] = $clientIp;
        }
        $this->where(['iotId'=>$iotId])->update($data);
    }
}
